package com.soc.web.client;

import java.util.Arrays;
import java.util.List;

import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.soc.web.client.api.Element;
import com.soc.web.client.api.FancyBoxException;
import com.soc.web.client.api.FancyboxUtils;
import com.soc.web.client.api.markers.Loadable;

public class Gallery<T extends Media> extends Element implements Loadable<Panel> {
	private List<T> selection;
	private Panel displayPanel;
	private Layout layout;
	private String galleryClass;
	private String galleryId;
	
	public Gallery(Layout layout, List<T> selections) {
		for (T t : selections) {
			try {
				t.load();
			} catch (FancyBoxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		this.selection = selections;
		this.layout = layout;
		
		// Since we can't make any mods to the element without setElement the container panel must be decided now.
		if(this.layout == Layout.HORIZONTAL) {
			this.displayPanel = new HorizontalPanel();
		} else {
			this.displayPanel = new VerticalPanel();
		}
		
		galleryId = FancyboxUtils.getUniqueId();
		setElement(this.displayPanel.getElement());
	}
	
	public Gallery(Layout layout, T... selections) {
		this(layout, Arrays.asList(selections));		
	}
	
	@Override
	public Panel load() throws FancyBoxException {
		if(galleryClass == null) { 
			throw new FancyBoxException("You must have a gallery class");
		}
		
		if(this.selection != null) {
			for (Media item : this.selection) {
				item.setExternallyLoaded(true);
				item.setOptions(getOptions());
				item.getAnchor().addClassName(galleryClass);
				item.getAnchor().setRel(galleryId);				
				this.displayPanel.add(item);
//				item.load();
			}
			fancyboxRel(galleryId);
		} else {
			throw new FancyBoxException("No gallery items were presented to the gallery.");
		}
		return displayPanel;
	}
	
	@Override
	protected void onLoad() {
		try {
			load();
		} catch (FancyBoxException e) {
			e.printStackTrace();
		}
		super.onLoad();
	}
	
	public List<T> getSelection() {
		return selection;
	}
	
	public void setSelection(List<T> selection) {
		this.selection = selection;
	}
	
	public Panel getDisplayPanel() {
		return displayPanel;
	}
	
	public Layout getLayout() {
		return layout;
	}
	
	public void setGalleryClass(String galleryClass) {
		this.galleryClass = galleryClass;
	}
	
	public enum Layout {
		VERTICAL,
		HORIZONTAL
	}

	
}
